package io.gitee.h25094152.crypto.base64;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;




public class Base64Util {

    public static void main(String[] args) throws Exception {
        String code1 = Base64Util.enCodeBase64("abcd123中国");
        System.out.println("enCode = " + code1);
        String code2 = Base64Util.deCodeBase64(code1);
        System.out.println("deCode = " + code2);
    }

    /**
     * 加密Bases64
     * @param context
     * @return String
     */
    public static String enCodeBase64(String context) {
        byte[] bytes = context.getBytes();
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(bytes);
    }

    public static String enCodeBase64Byte(byte[] bytes){
        return Base64.getEncoder().encodeToString(bytes);
    }
    /**
     * 解密Base64
     * @param str
     * @return String
     * @throws IOException
     */
    public static String deCodeBase64(String str) throws IOException {

        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(str);
        return new String(bytes);
    }


    public static byte[] deCodeBase64Byte(String str) throws IOException {
        return Base64.getDecoder().decode(str);
    }

    // 字节流转为Base64
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return  Base64.getEncoder().encodeToString(buffer);
    }

    // base64解析输出文件
    public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
        byte[] buffer = Base64.getDecoder().decode(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

    // io转为base64
    public static String ioToBase64() throws IOException {
        String fileName = "d:/test.doc"; // 源文件
        String strBase64 = null;
        try {
            InputStream in = new FileInputStream(fileName);
            // in.available()返回文件的字节长度
            byte[] bytes = new byte[in.available()];
            // 将文件中的内容读入到数组中
            in.read(bytes);
            strBase64 = Base64.getEncoder().encodeToString(bytes); // 将字节流数组转换为字符串
            in.close();
        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return strBase64;
    }
}